#!/bin/sh /etc/rc.common
# Copyright (C) 2021-2023 ImmortalWrt.org

START=99
USE_PROCD=1

CONF="gowebdav"
PROG="/usr/bin/gowebdav"

start_service() {
	config_load "$CONF"

	local enabled
	config_get_bool enabled "config" "enabled" "0"
	[ "$enabled" -eq "1" ] || return 1

	local listen_port mount_dir read_only public_access
	local enable_auth username password
	local enable_https cert_cer cert_key

	config_get listen_port "config" "listen_port" "6086"
	config_get mount_dir "config" "mount_dir" "/mnt"
	config_get_bool read_only "config" "read_only" "0"
	config_get_bool public_access "config" "public_access" "0"

	config_get_bool enable_auth "config" "enable_auth" "0"
	config_get username "config" "username"
	config_get password "config" "password"

	config_get_bool enable_https "config" "enable_https" "0"
	config_get cert_cer "config" "cert_cer"
	config_get cert_key "config" "cert_key"

	[ -d "$mount_dir" ] || mkdir -p "$mount_dir"

	procd_open_instance
	procd_set_param command "$PROG"
	procd_append_param command -dir "$mount_dir"
	procd_append_param command -http ":$listen_port"
	[ "$read_only" -eq "0" ] || procd_append_param command -read-only

	if [ "$enable_auth" -eq "1" ]; then
		if [ -z "$username" ] || [ -z "$password" ]; then
			logger -p daemon.err -t "$CONF" "Authentication enabled with empty username or password!"
			return 1
		fi

		procd_append_param command -user "$username"
		procd_append_param command -password "$password"
	fi

	if [ "$enable_https" -eq "1" ]; then
		if [ -z "$cert_cer" ] || [ -z "$cert_key" ]; then
			logger -p daemon.err -t "$CONF" "HTTPS enabled with empty certificate!"
			return 1
		fi

		procd_append_param command -https-mode
		procd_append_param command -https-cert-file "$cert_cer"
		procd_append_param command -https-key-file  "$cert_key"
	fi

	procd_set_param limits core="unlimited"
	procd_set_param limits nofile="1000000 1000000"
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1

	if [ "$public_access" -eq "1" ]; then
		procd_open_data
		json_add_array firewall
			json_add_object ""
			json_add_string type rule
			json_add_string name "Allow-access-GoWebDav-at-$listen_port"
			json_add_string src "*"
			json_add_string dest_port "$listen_port"
			json_add_string proto tcp
			json_add_string target ACCEPT
			json_close_object
		json_close_array
		procd_close_data
	fi

	procd_close_instance
}

service_started() {
	procd_set_config_changed firewall
}

service_stopped() {
	procd_set_config_changed firewall
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
